<?php
	/**
	* 对变量进行 JSON 编码
	* @param mixed value 待编码的 value ，除了resource 类型之外，可以为任何数据类型，该函数只能接受 UTF-8 编码的数据
	* @return string 返回 value 值的 JSON 形式
	*/
	function json_encode_ex($value){
		if(version_compare(PHP_VERSION, '5.4.0', '<')){
			$str = json_encode( $value);
			$str = preg_replace_callback("#\\\u([0-9a-f]{4})#i", function($matchs){
				return  iconv('UCS-2BE', 'UTF-8',  pack('H4',  $matchs[1]));
			}, $str);
			return $str;
		}else{
			return json_encode($value, JSON_UNESCAPED_UNICODE);
		}
	}
	//api加载class并初始化
	function includeclass($api,$class){
		$api->includefile($api->infodir."/".$class.".class.php");
		return $$class=new $class($api);
	}
	//解析图片
	function getimg($img,$mode=0,$smode=0){
		$img=explode(FILESPLIT,$img);
		foreach($img as &$value){
			if($smode==1){
				$value=explode('/',$value);
				$value[count($value)-1]='s_'.$value[count($value)-1];
				$value=implode('/',$value);
			}
			if(!empty($value)){
				$value=SITEROOTURL.$value;
			}
		}
		unset($value);
		if($mode==1){
			return $img[0];
		}else{
			return $img;
		}
	}
	//创建文件目录
	function create($dir){
		if(!is_dir($dir)){
			$temp=explode('/',$dir);
			$cur_dir='';
			for($i=0;$i<count($temp);$i++){
				$cur_dir .= $temp[$i].'/';
				if(!is_dir($cur_dir)){
					@mkdir($cur_dir,0777);
				}
			}
		}
	}
	//图片上传
	function creatfilesimg($files,$userid,$dirname,$simgh=80,$simgw=80,$maxfilesize=0){
		$return='';
		if(is_array($files['name'])){
			$file=array();
			foreach($files['name'] as $key=>$name){
				$file['name']=$files['name'][$key];
				$file['type']=$files['type'][$key];
				$file['tmp_name']=$files['tmp_name'][$key];
				$file['error']=$files['error'][$key];
				$file['size']=$files['size'][$key];
				$return.=creatfilesimg($file,$userid,$dirname,$simgh,$simgw,$maxfilesize).FILESPLIT;
			}
			$return=substr($return,0,strlen($return)-strlen(FILESPLIT));
		}else{
			$name=$files['name'];
			$file_ext=strtolower(substr($name,strrpos($name,".")+1,strlen($name)));
			if(is_uploaded_file($files["tmp_name"]) && $files["error"] == 0 && $file_ext!='' && $file_ext=checkfiletype($files["tmp_name"],$file_ext)) {
				$file_size = @filesize($files["tmp_name"]);
				if($maxfilesize==0){
					$maxfilesize=MAXFILESIZE*1024*1024;
				}
				if ($file_size <= 0 || $file_size>$maxfilesize){
					return false;
				}
				$upload_path=DOFILESPATH.$dirname.'/'.$userid.'/';
				//建立文件夹
				create($upload_path);
				$upload_file['name']=md5(uniqid(rand()));
				$upload_file['smallname']=$upload_path."s_".$upload_file['name'].'.'.$file_ext;
				$upload_file['filename']=$upload_path.$upload_file['name'].'.'.$file_ext;
				if(@move_uploaded_file($files["tmp_name"],$upload_file["filename"])){
					if($file_ext=="jpg"||$file_ext=="jpeg"||$file_ext=="gif"||$file_ext=="png"||$file_ext=="bmp"){
						$out=imgsresize($upload_file["filename"],intval($simgw),intval($simgh),$upload_file['smallname']);
					}
					$return.=$upload_path.$upload_file['name'].'.'.$file_ext;
				}
			}
		}
		return $return;
	}
	//验证图片类型
	function checkfiletype($f,$ftype){
		$accept=array("jpg","png","gif","bmp");
		if($ftype=="txt"){
			$fileType = 'txt';
		}else{
			$file = fopen($f, "rb");
			$bin = fread($file,4); //只读2字节
			$typeCode="";
			$strInfo = @unpack("C4chars", $bin);
			for($i=1;$i<=4;$i++){
				$strInfo['chars'.$i]=dechex($strInfo['chars'.$i]);
				if(strlen($strInfo['chars'.$i])==1){
					$strInfo['chars'.$i]="0".$strInfo['chars'.$i];
				}
				$typeCode=$typeCode.$strInfo['chars'.$i];
			}
			$fileType = '';
			if($typeCode=="504b0304"){
				$file = fopen($f, "rb");
				fseek($file,4);
				$bin = fread($file,1);
				$strInfo = @unpack("C1chars", $bin);
				$strInfo['chars']=dechex($strInfo['chars']);
				if(strlen($strInfo['chars'])==1){
					$strInfo['chars']="0".$strInfo['chars'];
				}
				$typeCode=$typeCode.$strInfo['chars'];
				switch ($typeCode){
					case '504b030414': $fileType = 'docx';break; /*docx/pptx/xlsx*/
					case '504b03040a': $fileType = 'zip';break;
				}
			}else{
				switch ($typeCode){
					case 'd0cf11e0': $fileType = 'doc';break; /*doc/ppt/xls/pot/pps/vsd/wps/dps/et*/
					case '7b5c7274': $fileType = 'rtf';break;
					case '25504446': $fileType = 'pdf';break;
					case 'ffd8ffe1': $fileType = 'jpg';break;
					case 'ffd8ffe0': $fileType = 'jpg';break;
					case '89504e47': $fileType = 'png';break;
					case '38425053': $fileType = 'psd';break;
					case '424d3803': $fileType = 'bmp';break;
					case '47494638': $fileType = 'gif';break;
					default: $fileType='wrong';
				}
			}
			fclose($file);
		}
		if(!in_array($fileType, $accept)){
			return false;
		}elseif($fileType=="doc"){
			if($ftype!="doc" && $ftype!="ppt" && $ftype!="xls" && $ftype!="pot" && $ftype!="pps" && $ftype!="vsd" && $ftype!="wps" && $ftype!="dps" && $ftype!="et"){
				return false;
			}
		}elseif($fileType=="docx"){
			if($ftype!="docx" && $ftype!="pptx" && $ftype!="xlsx"){
				return false;
			}
		}
		return $fileType;
	}
	//生成缩略图
	function imgsresize($img, $w, $h, $newfilename) { 
		//Check if GD extension is loaded
		if (!extension_loaded('gd') && !extension_loaded('gd2')) {
			trigger_error("GD is not loaded", E_USER_WARNING);
			return false;
		}
		
		//Get Image size info
		$imgInfo = getimagesize($img);
		switch ($imgInfo[2]) {
			case 1: $im = imagecreatefromgif($img); break;
			case 2: $im = imagecreatefromjpeg($img);  break;
			case 3: $im = imagecreatefrompng($img); break;
			default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
		}
		
		//If image dimension is smaller, do not resize
		if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
			$nHeight = $imgInfo[1];
			$nWidth = $imgInfo[0];
		}else{
			//yeah, resize it, but keep it proportional
			if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
				$nWidth = $w;
				$nHeight = $imgInfo[1]*($w/$imgInfo[0]);
			}else{
				$nWidth = $imgInfo[0]*($h/$imgInfo[1]);
				$nHeight = $h;
			}
		}
		$nWidth = round($nWidth);
		$nHeight = round($nHeight);
		
		$newImg = imagecreatetruecolor($nWidth, $nHeight);
		
		/* Check if this image is PNG or GIF, then set if Transparent*/  
		if($imgInfo[2] == 1){
			imagealphablending($newImg,false);
			$white = imagecolorallocate($newImg, 0xFF, 0xFF, 0xFF);
			imagefilledrectangle($newImg, 0, 0,$nWidth, $nHeight, $white);
			imagecolortransparent($newImg, $white);
		}else if($imgInfo[2]==3){
			imagealphablending($newImg,false);
			imagesavealpha($newImg,true);
			$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
			imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
			imagecolortransparent($newImg, $transparent);
		}
		imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
		//Generate the file, and rename it to $newfilename
		switch ($imgInfo[2]) {
			case 1: imagegif($newImg,$newfilename); break;
			case 2: imagejpeg($newImg,$newfilename);  break;
			case 3: imagepng($newImg,$newfilename); break;
			default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
		}
		imageDestroy($newImg);  
		return $imgInfo[2];
	}
	//创建唯一编号
	function getordernum($pre,$end=''){
		$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P');
		$orderSn=$yCode[intval(date('Y'))-2016].strtoupper(dechex(date('m'))).date('d').substr(time(),-5).substr(microtime(),2,5).sprintf('%02d',rand(0,99));
		return $pre.$orderSn.$end;
	}
?>